# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, Process, Project
from saltops.forms import PaginationForm

def factory(projects, procs):
    ## 遍历projects列表, 将存在于procs表中的成员项标记为'正在运行',
    ## 将未存在的成员标记为'未运行'

    for projIdx, proj in enumerate(projects):
        proj['status'] = 0
        proj['ports'] = []
        proj['pids'] = []
        proj['user'] = None
        proj['startDate'] = None
        for procIdx, proc in enumerate(procs):
            if proc['psStr'].find(proj['psStr']) == -1: continue
            proj['status'] = 1
            proj['pids'].append(proc['pid'])
            if not proj['user']: proj['user'] = proc['user']
            if not proj['startDate']: proj['startDate'] = proc['startDate']
            if proc['port']: proj['ports'].append(proc['port'])

    return projects

def query(req):
    form = PaginationForm(req.GET)
    if not form.is_valid():
        pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']

    minionId = req.GET['minionId']
    minion = Minion.objects.get(key = minionId)

    procs = Process.objects.filter(minion = minion)
    procs = [proc.parse() for proc in procs]

    projects = Project.objects.filter(minion = minion)
    count = projects.count()
    projects = projects[offset: offset + limit]

    projects = [proj.parse() for proj in projects]

    result = {
        'rows': factory(projects, procs), 
        'total': count
    }
    return JsonResponse(result)

def create(req):
    result = {
        'code': 1,
        'msg': 'success'
    }
    key = req.POST.get('minionId')
    exists = Minion.objects.filter(key = key).exists()
    if not exists:
        result['code'] = -1
        result['msg'] = '目标minion节点不存在'
        return JsonResponse(result)

    proj = {
        'minion': Minion.objects.get(key = key),
        'name': req.POST.get('name'),
        'owner': req.POST.get('owner', 'root'),
        'path': req.POST.get('path'),
        'start_cmd': req.POST.get('startCmd'),
        'ps_str': req.POST.get('psStr'),
        'remark': req.POST.get('remark'),
    }
    try:
        Project.objects.create(**proj)
        result['code'] = 1
        result['msg'] = 'success'
    except Exception, e:
        result['code'] = -1
        result['msg'] = e.message
    return JsonResponse(result)

def delete(req):
    result = {
        'code': 1,
        'msg': 'success'
    }
    id = req.POST.get('id', None)
    try:
        Project.objects.filter(id = id).delete()
    except Exception as e:
        result['code'] = -1
        result['msg'] = e.message
    return JsonResponse(result)
        
def update(req):
    pass

